package com.phospherus.flow.service

import com.phospherus.common.service.impl.BaseServiceImpl
import com.phospherus.flow.entity.HiveToDo
import com.phospherus.flow.entity.WorkFlowInst
import com.phospherus.flow.repository.HiveToDoRepository
import com.phospherus.user.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * @author songjinlong
 * @version 1.0
 * @since 2018/1/3
 */
@Service
class HiveToDoService : BaseServiceImpl<HiveToDo, Long, HiveToDoRepository>() {
    @Autowired
    lateinit var formService: FormService
    @Autowired
    lateinit var formInstService: FormInstService

    fun addHiveToDo(currWorkFlowInst: WorkFlowInst, nextWorkFlowInst: WorkFlowInst, map: MutableMap<String, Any>) {
        var formInstId = currWorkFlowInst.formInstId
        var user = map["USER"] as User
        var hiveToDo = repository.findByFormInstIdAndUserId(formInstId, user.id) ?: HiveToDo()
        var form = formService.findOne(currWorkFlowInst.flowId)
        var formInst = formInstService.findOne(formInstId)
        var currUserName = nextWorkFlowInst.currUserName ?: "-"
        with(hiveToDo) {
            this.formInstId = formInstId
            this.formId = currWorkFlowInst.formId
            this.flowId = currWorkFlowInst.flowId
            this.flowPath = form.flowPath
            this.flowName = form.formName
            this.userId = user.id
            this.userName = user.userName
            this.currUserName = currUserName
            this.createUserName = formInst.createUserName
            this.formServiceName = form.formServiceName
            this.formInstStatus = nextWorkFlowInst.workFlowType
            this.orderCode = formInst.orderCode
            this.ftcCode = formInst.ftcCode
            this.dtcCode = formInst.dtcCode
            this.buyerName = formInst.buyerName
            this.arrivalTime = currWorkFlowInst.arrivalTime
            this.finishTime = currWorkFlowInst.finishTime
        }
        save(hiveToDo)
        modifyCurrUserName(formInstId, currUserName)
    }

    fun modifyCurrUserName(formInstId: Long?, currUserName: String?) = repository.modifyCurrUserName(formInstId, currUserName)

}